package com.googlecode.monitoring.db.model;



import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;

public class MaxAgeOfData implements Serializable {
	private String age;
	private AgeType ageType;
	private Integer amount;

	public MaxAgeOfData(String age) {
		this.age = age;
		String[] str = age.split("\\s+");
		this.amount = Integer.valueOf(str[0]);
		String ageTypeString = str[1];
		for (AgeType type : AgeType.values()) {
			if (ageTypeString.equalsIgnoreCase(type.name())) {
				ageType = type;
			}
		}
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	/**
	 * Check if given date/time is valid now, according to the ageType and amount fields. All fields
	 * less significant than the age type field are ignored when doing the check.
	 * 
	 * @param candidate
	 */
	public boolean isValid(Calendar candidate) {
		Calendar now = Calendar.getInstance();
		Date maxValidToDate = now.getTime();
		switch (ageType) {
            
			case YEAR:
			case MONTH:
			case DAY:
			case HOUR:
			case MINUTE:
			case SECOND:
				clearLessSignificantFields(candidate, ageType.getCalendarField().intValue());
				clearLessSignificantFields(now, ageType.getCalendarField().intValue());
				candidate.add(ageType.getCalendarField(), amount);
				maxValidToDate = candidate.getTime();
				break;
//			case BANKINGDAY:
//				clearLessSignificantFields(candidate, Calendar.DAY_OF_WEEK);
//				clearLessSignificantFields(now, Calendar.DAY_OF_WEEK);
//				maxValidToDate = NorwegianDateUtil.addWorkingDaysToDate(candidate.getTime(), amount);
//				break;
		}
		return !maxValidToDate.before(now.getTime());
	}
	
	private void clearLessSignificantFields(Calendar cal, int minValidCalendarField) {
		for (int i = minValidCalendarField + 1; i < Calendar.FIELD_COUNT; i++) {
			cal.clear(i);
		}
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder();
		sb.append("MaxAgeOfData");
		sb.append("{age='").append(age).append('\'');
		sb.append('}');
		return sb.toString();
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}

		MaxAgeOfData that = (MaxAgeOfData) o;

		if (age != null ? !age.equals(that.age) : that.age != null) {
			return false;
		}

		return true;
	}

	@Override
	public int hashCode() {
		return age != null ? age.hashCode() : 0;
	}
}
